<template>
  <div>
    <div>
      <el-row>
        <el-col>
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['advertising:management:rules:add']"
            style="margin: 20px 20px 20px 20px"
          >
            新增广告配置
          </el-button>
        </el-col>
      </el-row>
    </div>
    <el-table
      v-loading="loading"
      :data="postList"
      :default-sort="{ prop: 'postId', order: 'descending' }"
    >
      <el-table-column align="center" label="推荐信息标题" prop="title" />
      <el-table-column align="center" label="位置" prop="positionId">
        <template #default="scope">
          <span>{{
            positionList.filter((item) => item.id === scope.row.positionId)[0]
              .title
          }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="类型" prop="type">
        <template #default="scope">
          <span v-if="scope.row.type == 0">图片</span>
          <span v-if="scope.row.type == 1">代码</span>
          <span v-if="scope.row.type == 2">视频</span>
          <span
            v-if="
              scope.row.type != 0 && scope.row.type != 1 && scope.row.type != 2
            "
            >未知</span
          >
        </template>
      </el-table-column>
      <el-table-column align="center" label="推荐标签" prop="tag" />
      <el-table-column align="center" label="链接地址" prop="link">
        <template #default="scope">
          <el-tooltip
            class="item"
            effect="dark"
            :content="scope.row.link"
            placement="top"
          >
            {{ scope.row.link ? scope.row.link.substring(0, 10) : "" }}
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column align="center" label="封面地址" prop="cover">
        <template #default="scope">
          <el-tooltip
            class="item"
            effect="dark"
            :content="scope.row.cover"
            placement="top"
          >
            {{ scope.row.cover ? scope.row.cover.substring(0, 10) : "" }}
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column align="center" label="代码内容" prop="codeContent">
        <template #default="scope">
          <el-tooltip
            class="item"
            effect="dark"
            :content="scope.row.codeContent"
            placement="top"
          >
            {{
              scope.row.codeContent
                ? scope.row.codeContent.substring(0, 10)
                : ""
            }}
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column align="center" label="视频地址" prop="video">
        <template #default="scope">
          <el-tooltip
            class="item"
            effect="dark"
            :content="scope.row.video"
            placement="top"
          >
            {{ scope.row.video ? scope.row.video.substring(0, 10) : "" }}
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column align="center" label="摘要信息" prop="remarks">
        <template #default="scope">
          <el-tooltip
            class="item"
            effect="dark"
            :content="scope.row.remarks"
            placement="top"
          >
            {{ scope.row.remarks ? scope.row.remarks.substring(0, 10) : "" }}
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column align="center" label="开始时间" prop="startTime" />
      <el-table-column align="center" label="结束时间" prop="endTime" />

      <el-table-column align="center" label="是否已启用" prop="isEnable">
        <template #default="scope">
          <span v-if="scope.row.isEnable == 0">否</span>
          <span v-if="scope.row.isEnable == 1">是</span>
          <span v-if="scope.row.isEnable != 0 && scope.row.isEnable != 1"
            >未知</span
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['advertising:management:rules:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['advertising:management:rules:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改广告配置对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="postRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="推荐信息标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入信息标题" />
        </el-form-item>

        <el-form-item label="广告位置" prop="positionId">
          <el-select v-model="form.positionId" placeholder="请选择广告位置">
            <el-option
              :label="item.title"
              :value="item.id"
              v-for="item in positionList"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type" @change="handleChange">
            <el-radio :value="0">图片</el-radio>
            <el-radio :value="1">代码</el-radio>
            <el-radio :value="2">视频</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否启用" prop="isEnable">
          <el-radio-group v-model="form.isEnable">
            <el-radio :value="0">否</el-radio>
            <el-radio :value="1">是</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="推荐标签" prop="tag">
          <el-input v-model="form.tag" placeholder="推荐标签" />
        </el-form-item>

        <el-form-item label="链接地址" prop="link">
          <el-input
            v-model="form.link"
            placeholder="请输入链接地址 例如：https://www.baidu.com/"
          />
        </el-form-item>

        <!-- 类型单选框选择显示与隐藏 -->
        <el-form-item
          label="代码内容"
          prop="codeContent"
          v-if="form.type === 1"
        >
          <el-input
            v-model="form.codeContent"
            type="textarea"
            show-word-limit
            placeholder="请输入代码内容"
          />
        </el-form-item>

        <el-form-item label="图片" prop="cover;" v-if="form.type === 0">
          <image-upload v-model:modelValue="form.cover" :limit="1" />
        </el-form-item>

        <el-form-item label="视频" prop="video" v-if="form.type === 2">
          <VideoUpload v-model:modelValue="form.video" />
        </el-form-item>

        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="请输入开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="请输入结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="摘要" prop="remarks">
          <el-input
            v-model="form.remarks"
            type="textarea"
            show-word-limit
            maxlength="60"
            placeholder="请输入摘要内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import VideoUpload from "./VideoUpload";
import { ref } from "vue";
import {
  getAdvertsApi,
  addAdvertsApi,
  deleteAdvertsApi,
  getAdvertsByIdApi,
  putAdvertsApi,
} from "@/api/advertising/configure";
import { getAllPositionApi } from "@/api/advertising/location";

const { proxy } = getCurrentInstance();
const postList = ref([]);
const loading = ref(true);
const total = ref(0);
const open = ref(false);
const title = ref("");
const data = reactive({
  form: {
    title: "", //推荐标题
    positionId: "", //广告位置
    type: "", //类型
    tag: "", //推荐标签
    link: "", //链接地址
    codeContent: "", //代码内容
    cover: "", //封面地址
    video: "", //视频地址
    remarks: "", //摘要信息
    startTime: "", //开始时间
    endTime: "", //结束时间
    isEnable: "", //是否启用
  },

  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },

  rules: {
    title: [{ required: true, message: "推荐标题不能为空", trigger: "blur" }],
    positionId: [
      { required: true, message: "广告位置不能为空", trigger: "change" },
    ],
    link: [
      { required: true, message: "请输入链接地址", trigger: "blur" },
      {
        pattern:
          /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/|www\.)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/,
        message: "链接地址格式不正确，正确格式为：https://www.baidu.com/",
        trigger: "blur",
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询广告信息配置列表 */
function getList() {
  loading.value = true;
  getAdvertsApi(queryParams.value).then((response) => {
    postList.value = response.rows;
    total.value = Number(response.total);
    loading.value = false;
  });
}

const rest = () => {
  form.value = {
    title: "",
    positionId: "",
    type: "",
    tag: "",
    link: "",
    codeContent: "",
    cover: "",
    video: "",
    remarks: "",
    startTime: "",
    endTime: "",
    isEnable: "",
  };
  proxy.resetForm("postRef");
};

const positionList = ref([]);
/**
 * 查询全部广告位置
 */
const getPosition = () => {
  getAllPositionApi().then((res) => {
    if (res.code == 200) {
      positionList.value = res.data;
    }
  });
};
getPosition();

/** 新增按钮操作 */
function handleAdd() {
  rest();
  open.value = true;
  title.value = "新增广告配置";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  rest();
  const postId = row.id;
  getAdvertsByIdApi(postId).then((response) => {
    form.value = {
      id: response.data.id,
      title: response.data.title,
      positionId: response.data.positionId,
      type: Number(response.data.type),
      tag: response.data.tag,
      link: response.data.link,
      codeContent: response.data.codeContent,
      cover: response.data.cover,
      video: response.data.video,
      remarks: response.data.remarks,
      startTime: response.data.startTime,
      endTime: response.data.endTime,
      isEnable: response.data.isEnable,
    };

    open.value = true;
    title.value = "修改广告配置";
  });
}

const handleChange = () => {
  if (form.value.type === 0) {
    console.log("图片", form.value.type);
    form.value.codeContent = "";
    form.value.video = "";
  } else if (form.value.type === 1) {
    console.log("代码", form.value.type);
    form.value.cover = "";
    form.value.video = "";
  } else if (form.value.type === 2) {
    console.log("视频", form.value.type);
    form.value.cover = "";
    form.value.codeContent = "";
  }
};

/** 取消按钮 */
function cancel() {
  rest();
  open.value = false;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["postRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        putAdvertsApi(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addAdvertsApi(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const postIds = row.id;
  proxy.$modal
    .confirm('是否确认删除广告为"' + row.title + '"的数据项？')
    .then(function () {
      return deleteAdvertsApi(postIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

getList();
</script>
<style scoped>
:deep(.el-form-item) {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
</style>
